package com.jason.unpluggedsuperstar;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;
import android.widget.TextView;

import com.android.dataframework.DataFramework;
import com.google.ytd.YTDUploader;
import com.jason.unpluggedsuperstar.ui.BeAStar;
import com.jason.unpluggedsuperstar.ui.PagerAdapter;
import com.jason.unpluggedsuperstar.ui.Stream;
import com.jason.unpluggedsuperstar.utils.VideoUtils;

public class UnpluggedSuperStarActivity extends FragmentActivity implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener{
	/** Called when the activity is first created. */
	
	/**
	 * Public
	 */
	public static ProgressDialog mProgressDialog;

	/**
	 * Private
	 */
	private Context mContext;
	private YTDUploader mYTDUploader = null;
	private TabHost mTabHost;
	private ViewPager mViewPager;
	private HashMap<String, TabInfo> mapTabInfo = new HashMap<String, UnpluggedSuperStarActivity.TabInfo>();
	private PagerAdapter mPagerAdapter;
	private BeAStar mBeAStar;

	/**
	 * Maintains extrinsic info of a tab's construct
	 */
	private class TabInfo {
		private String tag;
		private Class<?> clss;
		private Bundle args;
		private Fragment fragment;

		TabInfo(String tag, Class<?> clazz, Bundle args) {
			this.tag = tag;
			this.clss = clazz;
			this.args = args;
		}

	}

	/**
	 * A simple factory that returns dummy views to the Tabhost
	 */
	class TabFactory implements TabContentFactory {

		private final Context mContext;

		/**
		 * @param context
		 */
		public TabFactory(Context context) {
			mContext = context;
		}

		/**
		 * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
		 */
		public View createTabContent(String tag) {
			View v = new View(mContext);
			v.setMinimumWidth(0);
			v.setMinimumHeight(0);
			return v;
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		mContext = this.getApplicationContext();
		mProgressDialog = new ProgressDialog(UnpluggedSuperStarActivity.this);
		
		try {
			DataFramework.getInstance().open(getApplicationContext(), "com.jason.unpluggedsuperstar");
			//Insert
			/*Entity entity = new Entity("video_list");
			entity.setValue("title","test_title");
			entity.setValue("description", "test_description");
			boolean saved = entity.save();*/
			
			//Select
			/*Cursor notesCursor = DataFramework.getInstance().getCursor("video_list");
			while(notesCursor.moveToNext()){
				Log.d("field 1", String.valueOf(notesCursor.getString(1)));
			}*/
	        
			//Delete
			/*Entity entity = new Entity("video_list",(long) 1.0);
			entity.delete();*/
			
			//Update
			/*List<Entity> data = DataFramework.getInstance().getEntityList("video_list");
			for(int i=0;i<data.size();i++){
				Entity e = data.get(i);
				e.setValue("title", "test_title_updated");
				e.save();
			}*/
			
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/*mYTDUploader = new YTDUploader(UnpluggedSuperStarActivity.this);
		mYTDUploader.checkCriteria(new accessListener() {
			@Override
			public void onVerified() {
				Log.e("onVerified", "onVerified");
			}

			@Override
			public void onError(String error) {
				Log.e("error", error);
			}
		});

		mYTDUploader.setProgressListener(new progressListener() {
			@Override
			public void onProgressUpdate(double progress) {
			}

			@Override
			public void onError(String error) {
				// TODO Auto-generated method stub
				Log.e("error", error);
			}

			@Override
			public void onSuccess(String videoId) {
				// TODO Auto-generated method stub
				Log.e("videoId", videoId);
			}
		});
		mYTDUploader.upload(
				Uri.parse("content://media/external/video/media/3"),
				"test 789", "test 789");*/
		
		// Initialise the TabHost
		this.initialiseTabHost(savedInstanceState);
		// Intialise ViewPager
		this.intialiseViewPager();
	}
	
	/**
     * Initialise ViewPager
     */
    private void intialiseViewPager() {

		List<Fragment> fragments = new Vector<Fragment>();
		this.mPagerAdapter  = new PagerAdapter(super.getSupportFragmentManager(), fragments);
		
		mBeAStar = (BeAStar) Fragment.instantiate(this, BeAStar.class.getName());
		fragments.add(mBeAStar);
		fragments.add(Fragment.instantiate(this, Stream.class.getName()));
		
		this.mViewPager = (ViewPager)super.findViewById(R.id.viewpager);
		this.mViewPager.setAdapter(this.mPagerAdapter);
		this.mViewPager.setOnPageChangeListener(this);
    }
    
    /**
	 * Initialise the Tab Host
	 */
	private void initialiseTabHost(Bundle args) {
		mTabHost = (TabHost)findViewById(R.id.tabhost);
        mTabHost.setup();
        
        TabInfo tabInfo = null;
        UnpluggedSuperStarActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator(createTabView(this.mTabHost.getContext(),"Tab 1")), ( tabInfo = new TabInfo("Tab1", BeAStar.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        
        UnpluggedSuperStarActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator(createTabView(this.mTabHost.getContext(),"Tab 2")), ( tabInfo = new TabInfo("Tab2", Stream.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        
        //UnpluggedSuperStarActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab 3"), ( tabInfo = new TabInfo("Tab3", null, args)));
        //this.mapTabInfo.put(tabInfo.tag, tabInfo);

        mTabHost.setOnTabChangedListener(this);
	}
	
	/**
	 * Add Tab content to the Tabhost
	 * @param activity
	 * @param tabHost
	 * @param tabSpec
	 * @param clss
	 * @param args
	 */
	private static void AddTab(UnpluggedSuperStarActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
		// Attach a Tab view factory to the spec
		tabSpec.setContent(activity.new TabFactory(activity));
        tabHost.addTab(tabSpec);
	}
	
	private static View createTabView(final Context context, final String text) {
        View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
        TextView tv = (TextView) view.findViewById(R.id.tabsText);
        tv.setText(text);
        return view;
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int arg0) {
		this.mTabHost.setCurrentTab(arg0);
	}

	@Override
	public void onTabChanged(String arg0) {
		//TabInfo newTab = this.mapTabInfo.get(tag);
		int pos = this.mTabHost.getCurrentTab();
		this.mViewPager.setCurrentItem(pos);
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (requestCode == VideoUtils.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
	    	
	    	if(resultCode == RESULT_OK){
	    		Uri u = null;
	            if (VideoUtils.hasImageCaptureBug()) {
	                File fi = new File("/sdcard/tmp");
	            } else {
	                u = data.getData();
	            }
	            
	            VideoUtils.createVideoEntry(mContext,"999","111",u.toString());
	            mBeAStar.reloadVideoList();
	    	}
	    	
	    }
	}
}